/**
 * author:Administrator
 * date:2015/7/27
 * desc:TODO
 */
"use strict";

var model = require('../../model/mongo/permission.js');
let fout = require('../../common/function.js').formatOutput;

function MongoDao() {
    let self = this instanceof MongoDao ? this : new MongoDao();
    return self;
}
module.exports = MongoDao;
var theProto = MongoDao.prototype;

theProto.getUniqueName = function (gName, name) {
    return gName + ':' + name
};

theProto.parseUniqueName = function (uniqueName) {
    let arr = uniqueName.split(':');
    return {
        groupName: arr[0],
        name: arr[1]
    }
};

theProto.saveOne = function*(json) {
    var entity = {
        groupName: json.groupName,
        name: json.name,
        uniqueName: json.uniqueName
    };
    var query = {uniqueName: json.uniqueName};

    // in case of duplicate groupName:name
    let result = yield model.findOneAndUpdate(query, entity, {upsert: true, new: true});
    return fout(0, null, result);
};

theProto.getAll = function*() {
    // aggregate
    let result = yield model.find(); //get all
    let ret = result.map(function (item) {
        return __outputFilter(item._doc);
    });
    return ret;
};

theProto.saveAll = function*(list) {
    let result = [];
    while (list.length > 0) {
        let json = list.shift();
        let ret = yield this.saveOne(json);
        ret = ret.result._doc;
        __outputFilter(ret);
        result.push(ret);
    }

    return fout(0, null, result);
};

function __outputFilter(doc) {
    delete doc._id;
    delete doc.__v;
    delete doc.updateAt;
    delete doc.createdAt;
    delete doc.uniqueName;
    return doc;
}

